angular.module('ProduceWork').controller('MOCompleteRptController', ['$scope', '$http', 'PublicService', 'PublicModule', 'PublicEnum', 'PublicFunction', 'BarcodeEnum', '$location', '$modal', 'Authentication',
	function($scope, $http, PublicService, PublicModule, PublicEnum, PublicFunction, BarcodeEnum, $location, $modal, Authentication) {

		PublicModule.initModule($scope, 'RcvRecord');
		PublicModule.initModule($scope, '_RcvRecord');

		$scope.Module._RcvRecord.LoadMode = PublicEnum.LoadMode.CacheAndNoPaging;
		$scope.Module._RcvRecord.PageSize = 15;

		$scope.Module.RcvRecord.LoadMode = PublicEnum.LoadMode.CacheAndNoPaging;
		$scope.Module.RcvRecord.PageSize = 15;
		$scope.Module.RcvRecord.Populate = [{
			path: 'BarcodeMaster',
			select: 'Barcode MOLotNumber ShipLotNumber'
		}, {
			path: 'ItemMaster',
			select: 'Name Specification'
		}, {
			path: 'BusinessDocID',
			select: 'Code',
			model: 'MO'
		}, {
			path: 'RcvUser',
			select: 'Name Department',
			model: 'User',
			populate: {
				path: 'Department',
				select: 'Name',
				model: 'Department'
			}
		}, {
			path: 'ConnectArea',
			select: 'Name'
		}];

		//日期
		var curday = calCurrentMonthTime(true, 0);
		var lastweekstart = calCurrentMonthTime(true, 1) + ' 00:00:00';
		var lastweekend = calCurrentMonthTime(false, 1) + ' 23:59:59';
		var curweekstart = calCurrentMonthTime(true, 2) + ' 00:00:00';
		var curweekend = calCurrentMonthTime(false, 2) + ' 23:59:59';
		var lastmonthstart = calCurrentMonthTime(true, 3) + ' 00:00:00';
		var lastmonthend = calCurrentMonthTime(false, 3) + ' 23:59:59';
		var curmonthstart = calCurrentMonthTime(true, 4) + ' 00:00:00';
		var curmonthend = calCurrentMonthTime(false, 4) + ' 23:59:59';

		var condition = {
			RcvBusinessType: 0,
			RcvDateTime: {
				"$gte": curweekstart,
				"$lte": curweekend
			}
		};

		$scope.Module.RcvRecord.PageSize = 15;
		$scope.Module.RcvRecord.load(condition);

		$scope.ProductComplete = true;
		$scope.ConnectArea = false;
		$scope.All = false;
		$scope.Day = false;
		$scope.LastWeek = false;
		$scope.CurrentWeek = true;
		$scope.LastMonth = false;
		$scope.CurrentMonth = false;
		$scope.AllDay = false;


		//成品完工
		$scope.cbRcvRpt = function() {
			if ($scope.ProductComplete) {
				$scope.ConnectArea = false;
				$scope.All = false;
				$scope.$digest();
				if ($scope.Day) {
					query(0, 0);
				} else if ($scope.LastWeek) {
					query(0, 1);
				} else if ($scope.CurrentWeek) {
					query(0, 2);
				} else if ($scope.LastMonth) {
					query(0, 3);
				} else if ($scope.CurrentMonth) {
					query(0, 4);
				} else if ($scope.AllDay) {
					query(0, 5);
				};

			} else {
				$scope.ProductComplete = true;
				$scope.$digest();
			}
		};

		//交接区入库
		$scope.cbConnect = function() {
			if ($scope.ConnectArea) {
				$scope.ProductComplete = false;
				$scope.All = false;
				$scope.$digest();

				if ($scope.Day) {
					query(1, 0);
				} else if ($scope.LastWeek) {
					query(1, 1);
				} else if ($scope.CurrentWeek) {
					query(1, 2);
				} else if ($scope.LastMonth) {
					query(1, 3);
				} else if ($scope.CurrentMonth) {
					query(1, 4);
				} else if ($scope.AllDay) {
					query(1, 5);
				};
			} else {
				$scope.ConnectArea = true;
				$scope.$digest();
			}
		};

		//全部类型
		$scope.cbRcvAll = function() {
			if ($scope.All) {
				$scope.ProductComplete = false;
				$scope.ConnectArea = false;
				$scope.$digest();

				if ($scope.Day) {
					query(2, 0);
				} else if ($scope.LastWeek) {
					query(2, 1);
				} else if ($scope.CurrentWeek) {
					query(2, 2);
				} else if ($scope.LastMonth) {
					query(2, 3);
				} else if ($scope.CurrentMonth) {
					query(2, 4);
				} else if ($scope.AllDay) {
					query(2, 5);
				};
			} else {
				$scope.All = true;
				$scope.$digest();
			}
		};

		//当天
		$scope.cbCurrentDay = function() {
			if ($scope.Day) {
				$scope.LastWeek = false;
				$scope.CurrentWeek = false;
				$scope.LastMonth = false;
				$scope.CurrentMonth = false;
				$scope.AllDay = false;
				$scope.$digest();

				if ($scope.ProductComplete) {
					query(0, 0);
				} else if ($scope.ConnectArea) {
					query(1, 0);
				} else if ($scope.All) {
					query(2, 0);
				};
			} else {
				$scope.Day = true;
				$scope.$digest();
			}
		};

		//上周
		$scope.cbLastWeek = function() {
			if ($scope.LastWeek) {
				$scope.Day = false;
				$scope.CurrentWeek = false;
				$scope.LastMonth = false;
				$scope.CurrentMonth = false;
				$scope.AllDay = false;
				$scope.$digest();

				if ($scope.ProductComplete) {
					query(0, 1);
				} else if ($scope.ConnectArea) {
					query(1, 1);
				} else if ($scope.All) {
					query(2, 1);
				};
			} else {
				$scope.LastWeek = true;
				$scope.$digest();
			}
		};

		//本周
		$scope.cbCurrentWeek = function() {
			if ($scope.CurrentWeek) {
				$scope.Day = false;
				$scope.LastWeek = false;
				$scope.LastMonth = false;
				$scope.CurrentMonth = false;
				$scope.AllDay = false;
				$scope.$digest();

				if ($scope.ProductComplete) {
					query(0, 2);
				} else if ($scope.ConnectArea) {
					query(1, 2);
				} else if ($scope.All) {
					query(2, 2);
				};
			} else {
				$scope.CurrentWeek = true;
				$scope.$digest();
			}
		};

		//上月
		$scope.cbLastMonth = function() {
			if ($scope.LastMonth) {
				$scope.Day = false;
				$scope.LastWeek = false;
				$scope.CurrentWeek = false;
				$scope.CurrentMonth = false;
				$scope.AllDay = false;
				$scope.$digest();

				if ($scope.ProductComplete) {
					query(0, 3);
				} else if ($scope.ConnectArea) {
					query(1, 3);
				} else if ($scope.All) {
					query(2, 3);
				};
			} else {
				$scope.LastMonth = true;
				$scope.$digest();
			}
		};

		//本月
		$scope.cbCurrentMonth = function() {
			if ($scope.CurrentMonth) {
				$scope.Day = false;
				$scope.LastWeek = false;
				$scope.CurrentWeek = false;
				$scope.LastMonth = false;
				$scope.AllDay = false;
				$scope.$digest();

				if ($scope.ProductComplete) {
					query(0, 4);
				} else if ($scope.ConnectArea) {
					query(1, 4);
				} else if ($scope.All) {
					query(2, 4);
				};
			} else {
				$scope.CurrentMonth = true;
				$scope.$digest();
			}
		};

		//全部时间
		$scope.cbAllDate = function() {
			if ($scope.AllDay) {
				$scope.Day = false;
				$scope.LastWeek = false;
				$scope.CurrentWeek = false;
				$scope.LastMonth = false;
				$scope.CurrentMonth = false;
				$scope.$digest();

				if ($scope.ProductComplete) {
					query(0, 5);
				} else if ($scope.ConnectArea) {
					query(1, 5);
				} else if ($scope.All) {
					query(2, 5);
				};
			} else {
				$scope.AllDay = true;
				$scope.$digest();
			}
		};

		//同步ERP
		$scope.btnSyncERPComplete = function() {
			$scope.Module._RcvRecord.Records=[];
			var rcds = new Array();
			for (var i in $scope.Module.RcvRecord.Records) {
				//if ($scope.Module.RcvRecord.Records[i].IsSelected && $scope.Module.RcvRecord.Records[i].RcvBusinessType == 0 && $scope.Module.RcvRecord.Records[i].ERPID == null) {
				//rcds.push($scope.Module.RcvRecord.Records[i]);
				//};
				if ($scope.Module.RcvRecord.Records[i].RcvBusinessType == 0 && ($scope.Module.RcvRecord.Records[i].ERPID == null || $scope.Module.RcvRecord.Records[i].ERPID.length == 0)) {
					rcds = rcds.concat(angular.copy($scope.Module.RcvRecord.Records[i]));
				};

			};
			var sumRcds = new Array();
			for (var i = 0; i < rcds.length; i++) {
				if (sumRcds.length == 0) { //追加
					sumRcds.push(rcds[i]);
				} else {
					for (var j = 0; j < sumRcds.length; j++) {
						if (rcds[i].BusinessDocID._id == sumRcds[j].BusinessDocID._id && rcds[i].RcvUser._id == sumRcds[j].RcvUser._id) { //按照MO和User汇总入库量
							sumRcds[j].RcvQty += rcds[i].RcvQty;
							continue;
						} else { //追加
							if (j == sumRcds.length - 1) {
								sumRcds.push(rcds[i]);
								break;
							};
						}
					};
				}
			};

			$scope.Module._RcvRecord.Records = sumRcds;
			// $scope.Module._RcvRecord.RecordCount = sumRcds.length;
			// $scope.Module._RcvRecord.firstPage();
			$scope.Module._RcvRecord.emitOnLoadEvent();
			// if (rcds.length < 1) {
			// 	PublicFunction.alert("请先勾选记录再执行该操作！", "操作有误");
			// } else {

			// };
		}

		//完工
		$scope.btnExecute = function() {
			var context = {
				CultureName: "zh-CN",
				EntCode: "1",
				OrgCode: "0001",
				UserCode: "demo"
			};
			var completeDTOList = [];

			for (var i = 0; i < $scope.Module._RcvRecord.Records.length; i++) {
				var rcd = $scope.Module._RcvRecord.Records[i];
				var QXCompleteData = {
					Lot: rcd.BarcodeMaster.ShipLotNumber,
					//Lot: 'fan-12',
					RcvQty: rcd.RcvQty,
					//RcvQty: 1,
					MOID: rcd.BusinessDocID._id,
					RcvUser: rcd.RcvUser._id
				};
				completeDTOList.push(QXCompleteData);
			};

			var params = {
				context,
				completeDTOList
			};

			$http.post("http://101.251.244.131/U9/RestServices/UFIDA.U9.ISV.QXCompleteSV.QX.ICreateCompleteSV.svc/Do", params).success(function(data) {
				for (var i = 0; i < data.d.length; i++) {
					for (var k = 0; k < $scope.Module._RcvRecord.Records.length; k++) {
						if ($scope.Module._RcvRecord.Records[k].BusinessDocID._id == data.d[i].MOID && $scope.Module._RcvRecord.Records[k].RcvUser._id == data.d[i].RcvUser) {
							if (data.d[i].ComID > 0) { //完工成功，回写完工ID
								$scope.Module._RcvRecord.Records[k].HandleResult = '成功';
							} else { //完工失败
								$scope.Module._RcvRecord.Records[k].HandleResult = '失败';
							}
							$scope.Module._RcvRecord.emitOnLoadEvent();
						}
					};

					for (var j = 0; j < $scope.Module.RcvRecord.Records.length; j++) {
						if ($scope.Module.RcvRecord.Records[j].BusinessDocID._id == data.d[i].MOID && $scope.Module.RcvRecord.Records[j].RcvUser._id == data.d[i].RcvUser && $scope.Module.RcvRecord.Records[j].RcvBusinessType == 0 && ($scope.Module.RcvRecord.Records[j].ERPID == null || $scope.Module.RcvRecord.Records[j].ERPID.length == 0)) {
							if (data.d[i].ComID > 0) { //完工成功，回写完工ID
								$scope.Module.RcvRecord.Records[j].ERPID = data.d[i].ComID;
								//$scope.Module.RcvRecord.save();
								$scope.Module.RcvRecord.updateByValue({
									_id: $scope.Module.RcvRecord.Records[j]._id
								}, {
									ERPID: data.d[i].ComID
								});
								$scope.Module.RcvRecord.emitOnLoadEvent();
							} else { //完工失败

							}
						};
					};

				};
			}).error(function(err) {
				console.log(err);
			});
		}

		function query(bussinessType, dateType) {
			//业务类型(成品完工、交接区入库、全部)
			//时间类型(当天、上周、本周、上月、本月、全部)

			var condit = {};

			if (bussinessType == 0) { //成品完工
				condit['RcvBusinessType'] = 0
			} else if (bussinessType == 1) { //交接区入库
				condit['RcvBusinessType'] = 1
			} else if (bussinessType == 2) { //全部

			};

			if (dateType == 0) { //当天
				condit['RcvDateTime'] = {
					'$gte': curday + ' 00:00:00',
					'$lte': curday + ' 23:59:59'
				}
			} else if (dateType == 1) { //上周
				condit['RcvDateTime'] = {
					'$gte': lastweekstart,
					'$lte': lastweekend
				}
			} else if (dateType == 2) { //本周
				condit['RcvDateTime'] = {
					'$gte': curweekstart,
					'$lte': curweekend
				}
			} else if (dateType == 3) { //上月
				condit['RcvDateTime'] = {
					'$gte': lastmonthstart,
					'$lte': lastmonthend
				}
			} else if (dateType == 4) { //本月
				condit['RcvDateTime'] = {
					'$gte': curmonthstart,
					'$lte': curmonthend
				}
			} else if (dateType == 5) { //全部

			};

			$scope.Module.RcvRecord.find(condit, null, $scope.Module.RcvRecord.Populate, function(rds) {
				$scope.Module.RcvRecord.Records = rds;
				//$scope.Module.RcvRecord.RecordCount = rds.length;
				//$scope.Module.RcvRecord.firstPage();
				$scope.Module.RcvRecord.emitOnLoadEvent();
			})
		}

		//计算起止时间
		function calCurrentMonthTime(isStartTime, dateType) { //isStartTime-判断起止，0-当天，1-上周，2-本周，3-上月，4-本月，5-全部
			var now = new Date(); //当前日期 
			var nowDayOfWeek = now.getDay(); //今天本周的第几天
			var nowDay = now.getDate(); //当前日
			var nowMonth = now.getMonth(); //当前月 
			var nowYear = now.getYear(); //当前年 
			nowYear += (nowYear < 2000) ? 1900 : 0; //
			var lastMonthDate = new Date(); //上月日期
			lastMonthDate.setDate(1);
			lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
			var lastYear = lastMonthDate.getYear();
			var lastMonth = lastMonthDate.getMonth();

			var rtnTime;
			if (dateType == 0) { //当天
				if (isStartTime) {
					var getCurrentDate = new Date(nowYear, nowMonth, nowDay);
					rtnTime = formatDate(getCurrentDate)
				} else {

				};
			} else if (dateType == 1) { //上周
				if (isStartTime) {
					var getUpWeekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 7 + 1);
					rtnTime = formatDate(getUpWeekStartDate);
				} else {
					var getUpWeekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek - 7 + 1));
					rtnTime = formatDate(getUpWeekEndDate);
				};
			} else if (dateType == 2) { //本周
				if (isStartTime) {
					var getWeekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1);
					rtnTime = formatDate(getWeekStartDate);
				} else {
					var getWeekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek + 1));
					rtnTime = formatDate(getWeekEndDate);
				};
			} else if (dateType == 3) { //上月
				if (isStartTime) {
					var getLastMonthStartDate = new Date(nowYear, lastMonth, 1);
					rtnTime = formatDate(getLastMonthStartDate);
				} else {
					var getLastMonthEndDate = new Date(nowYear, lastMonth, getMonthDays(nowYear, lastMonth));
					rtnTime = formatDate(getLastMonthEndDate);
				};
			} else if (dateType == 4) { //本月
				if (isStartTime) {
					var getMonthStartDate = new Date(nowYear, nowMonth, 1);
					rtnTime = formatDate(getMonthStartDate);
				} else {
					var getMonthEndDate = new Date(nowYear, nowMonth, getMonthDays(nowYear, nowMonth));
					rtnTime = formatDate(getMonthEndDate);
				};
			} else if (dateType == 5) { //全部
				if (isStartTime) {

				} else {

				};
			};

			return rtnTime;
		}

		//获得某月的天数
		function getMonthDays(nowYear, myMonth) {
			var monthStartDate = new Date(nowYear, myMonth, 1);
			var monthEndDate = new Date(nowYear, myMonth + 1, 1);
			var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
			return days;
		}

		//格式化时间
		function formatDate(date) {
			var myyear = date.getFullYear();
			var mymonth = date.getMonth() + 1;
			var myweekday = date.getDate();
			return (myyear + "-" + mymonth + "-" + myweekday);
		}
	}
]);